import { useEffect, useState } from 'react'

import CheckboxItem from './CheckboxItem'

function CheckboxList({
  data,
  hotDataList,
  medicineList,
  value,
  onChange
}: {
  data: any,
  hotDataList: any,
  value?: any,
  onChange: Function,
  medicineList?: any,
}) {

  const [checkedList, setSelectList] = useState<any>([]);

  useEffect(() => {
    if (medicineList && JSON.stringify(medicineList) != JSON.stringify(checkedList)) {
      setSelectList(medicineList)
    }
  }, [medicineList])

  useEffect(() => {
    onChange && onChange(checkedList);
  }, [checkedList])

  function onChangeValues(checkedValues: any) {
    console.log('checked = ', checkedValues);
    let newList = JSON.parse(JSON.stringify(checkedList));
    // const inde

    const index = newList?.findIndex((item: any) => item?.medicineId == checkedValues?.medicineId)
    if (index > -1) {
      newList.splice(index, 1);
      setSelectList(newList)
      // onChange && onChange(newList)
    } else {
      setSelectList((prv: any[]) => [...prv, checkedValues])
      // onChange && onChange([...newList, checkedValues])
    }
  }

  console.log('checkedList ===:>> ', medicineList, checkedList);

  return (
    <div style={{overflowY:'scroll',height:'500px'}}>
      <h3>常用药材</h3>
      {
        Array.isArray(hotDataList) && hotDataList?.map((item, index) => (
          <CheckboxItem checkedList={checkedList} key={index} {...item} onChange={onChangeValues} />
        ))
      }
      <h3>药材列表</h3>
      {
        Array.isArray(data) && data?.map((item, index) => (
          <div style={{width:'120px',margin:'5px',float:'left',overflow:'auto'}}>
            <CheckboxItem checkedList={checkedList} key={index} {...item} onChange={onChangeValues} />
          </div>
        ))
      }
    </div>
  )
}

export default CheckboxList;